package com.wh.wisdomsite.xbox.st.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wh.wisdomsite.xbox.core.XboxException;
import com.wh.wisdomsite.xbox.pojo.st.PurchaseDetailIn;
import com.wh.wisdomsite.xbox.pojo.st.StoreOutConfirmIn;
import com.wh.wisdomsite.xbox.st.dao.StoreMapper;
import com.wh.wisdomsite.xbox.st.dao.StoreOutRecordMapper;
import com.wh.wisdomsite.xbox.st.entity.*;
import com.wh.wisdomsite.xbox.st.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 库存serviceImpl
 * @version V1.0
 * @author: 杨世强
 * @Package com.wh.wisdomsite.xbox.st.service.impl
 * @date 2018-12-24 14:43
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Service("storeService")
@Transactional(rollbackFor = {Exception.class,RuntimeException.class})
public class StoreServiceImpl extends ServiceImpl<StoreMapper,Store> implements IStoreService {
    private static final Log logger = LogFactory.getLog(StoreServiceImpl.class);
    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private StoreOutRecordMapper storeOutRecordMapper;

    @Autowired
    private IContractService iContractService;

    @Autowired
    private IMaterialService iMaterialService;

    @Autowired
    private IStoreInRecordService iStoreInRecordService;

    @Autowired
    private IStoreOutRecordService iStoreOutRecordService;

    // 入库单号
    private String stiCode = "";
    // 时间格式化
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 时间格式化 不含时分秒
    private SimpleDateFormat sdfYmd = new SimpleDateFormat("yyyy-MM-dd");


    @Override
    public Page<Map<String, Object>> getMapsPage(Page page, Wrapper<Store> wrapper) {
        SqlHelper.fillWrapper(page,wrapper);
        page.setRecords(this.baseMapper.getMapsPage(page,wrapper));
        return page;
    }

    @Override
    public Page<Map<String, Object>> getMapsDetailPage(Page page,Wrapper<Store> wrapper) {
        SqlHelper.fillWrapper(page,wrapper);
        page.setRecords(this.baseMapper.getMapsList(page,wrapper));
        return page;
    }

    @Override
    public void savePull(List<StoreOutConfirmIn> storeOutRecordList, String userId) throws Exception {
        try{
            String stoCode = null;
            String uuid = UUID.randomUUID().toString().replace("-", "");
            for(StoreOutConfirmIn record:storeOutRecordList){
                String stId = record.getStId();
                Double stoNum = Double.parseDouble(record.getStoNum());
                //获取出库编号
                if(stoCode == null){
                    //获取合同单号
                    String number = "";
                    //获取合同单号
                    Map<String, Object> storeMap = storeMapper.getContract(stId);
                    if(storeMap.size() > 0){
                        Map<String, Object> contract = (Map)storeMap.get("contract");
                        String coCode = (String)contract.get("coCode");
                        String[] coCodeArr = coCode.split("_");
                        number = coCodeArr[1];
                    }
                    stoCode = iStoreOutRecordService.getStoCode(number);
                }else{
                    //获取最后四位数
                    String stoCodeLast = stoCode.substring(stoCode.lastIndexOf("_")+1);
                    //将数字加一操作
                    String stoCodePlus = iStoreInRecordService.getMaxNumber(stoCodeLast);
                    //合成最终编码
                    stoCode = stoCode.substring(0,stoCode.lastIndexOf("_")) + "_" + stoCodePlus;
                }
                //减少库存数量
                Store store = storeMapper.selectById(stId);
                Double storeNum = store.getStoreNum();
                //如果出库数量大于库存则不对库存操作
                if(stoNum <= storeNum){
                    Double storeNumResult = storeNum - stoNum;
                    Store store1 = new Store();
                    store1.setStId(stId);
                    store1.setStoreNum(storeNumResult);
                    storeMapper.updateById(store1);
                    //保存出库单
                    StoreOutRecord outRecord = new StoreOutRecord();
                    outRecord.setStorId(UUID.randomUUID().toString().replace("-",""));
                    outRecord.setStId(stId);
                    outRecord.setStoCode(stoCode);
                    outRecord.setStoNum(stoNum);
                    outRecord.setSameRecord(uuid);
                    outRecord.setKcSurplus(storeNumResult);
                    outRecord.setPurpose(record.getPurpose());
                    outRecord.setPullPerson(userId);
                    outRecord.setPullDate(sdf.parse(record.getPullDate()));
                    outRecord.setCreateBy(userId);
                    outRecord.setCreateDate(new Date());
                    storeOutRecordMapper.insert(outRecord);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public Page<Map<String, Object>> getStoreInAndOut(Page page, Wrapper<Store> wrapper) {
        SqlHelper.fillWrapper(page,wrapper);
        page.setRecords(this.baseMapper.getStoreInAndOut(page,wrapper));
        return page;
    }

    @Override
    public void savePutByLc(String userId, PurchaseDetailIn pdi,int index,String uuid) throws Exception{
        //获取合同编号
        String coId = pdi.getCoId();
        //截取合同编码
        Contract contract = iContractService.selectById(coId);
        String[] coCodeArr = contract.getCoCode().split("_");
        String coCode = "";
        if(coCodeArr.length == 1){
            coCode = "error";
        }else{
            coCode = coCodeArr[1];
        }
        //保存或更新库存表
        String maId = pdi.getMaId();
        String storeNum = pdi.getPurdNum();
        Store store = getStoreById(coId,maId,storeNum);
        //首次获取入库单号，往后不从数据库查询，直接对入库单号最后四位的记录次数做累加，提高效率
        if(index == 0){
            String purType = pdi.getPurType();
            //请购类型为合同内
            if(purType.equals("1")){
                purType = "RKN";
            }else{ //请购类型为合同外
                purType = "RKW";
            }
            stiCode = iStoreInRecordService.getStiCodeByType(purType,coCode);
        }else{
            //获取最后四位数
            String sitCodeLast = stiCode.substring(stiCode.lastIndexOf("_")+1);
            //将数字加一操作
            String sitCodePlus = iStoreInRecordService.getMaxNumber(sitCodeLast);
            //合成最终编码
            stiCode = stiCode.substring(0,stiCode.lastIndexOf("_"))+"_"+sitCodePlus;
        }
        StoreInRecord storeInRecord = new StoreInRecord();
        storeInRecord.setStirId(UUID.randomUUID().toString().replace("-",""));
        storeInRecord.setStId(store.getStId());
        storeInRecord.setKcCumulative(store.getStoreNum());
        storeInRecord.setStiCode(stiCode);
        storeInRecord.setPushPerson(userId);
        //流程入库方式
        storeInRecord.setStoreWay("1");
        //采购申请清单id
        storeInRecord.setPurdId(pdi.getPurdId());
        storeInRecord.setSameRecord(uuid);
        storeInRecord.setStoreNum(Double.valueOf(pdi.getPurdNum()));
        storeInRecord.setPushDate(sdf.parse(pdi.getPushDate()));
        storeInRecord.setRemark(pdi.getPushRemark());
        storeInRecord.setCreateBy(userId);
        storeInRecord.setCreateDate(new Date());
        iStoreInRecordService.insert(storeInRecord);
    }

    @Override
    public void savePutByRkt(String coId, String userId, HttpServletRequest request) throws Exception{
        try{
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String[] stirIds = request.getParameterValues("stirId");
            String[] materialNames = request.getParameterValues("materialName");
            String[] technicalParameters = request.getParameterValues("technicalParameter");
            String[] brands = request.getParameterValues("brand");
            String[] standardTypes = request.getParameterValues("standardType");
            String[] meteringUnits = request.getParameterValues("meteringUnit");
            String[] unitPrices = request.getParameterValues("unitPrice");
            String[] storeNums = request.getParameterValues("storeNum");
            String[] pushDates = request.getParameterValues("pushDate");
            String[] remarks = request.getParameterValues("remark");
            //截取合同编码
            Contract contract = iContractService.selectById(coId);
            String[] coCodeArr = contract.getCoCode().split("_");
            String coCode = "";
            if(coCodeArr.length == 1){
                coCode = "error";
            }else{
                coCode = coCodeArr[1];
            }
            String stiCode = null;
            //遍历前端传入的所有行
            for(int index = 0; index < stirIds.length; index ++ ){
                //验证数据是否正确
                if(StringUtils.isEmpty(materialNames[index])){
                    throw new XboxException("物料名称不能为空");
                }
                if(StringUtils.isEmpty(standardTypes[index])){
                    throw new XboxException("物料规格型号不能为空");
                }
                if(StringUtils.isEmpty(unitPrices[index])){
                    throw new XboxException("物料采购单价不能为空");
                }
                if(StringUtils.isEmpty(storeNums[index])){
                    throw new XboxException("入库数量不能为空");
                }
                /*if(StringUtils.isEmpty(pushPersons[index])){
                    throw new XboxException("入库人员不能为空");
                }*/
                //根据一行录入的数据，创建物料
                Material material = new Material();
                material.setMaterialName(materialNames[index]);
                material.setStandardType(standardTypes[index]);
                material.setStandardType(brands[index]);
                material.setStandardType(technicalParameters[index]);
                material.setMeteringUnit(meteringUnits[index]);
                material.setUnitPrice(Double.valueOf(unitPrices[index]));
                //获取物料ID
                String maId = iMaterialService.getMaId(material);
                if(maId == null){
                    throw new XboxException("获取物料ID发生异常");
                }
                String storeNum = storeNums[index];
                //获取库存对象
                Store store = getStoreById(coId,maId,storeNum);
                String stId = store.getStId();
                Double curStoreNum = store.getStoreNum();
                //首次获取入库单号，往后不从数据库查询，直接对入库单号最后四位的记录次数做累加，提高效率
                if(stiCode == null){
                    stiCode = iStoreInRecordService.getStiCodeByType("RKT",coCode);
                }else{
                    //获取最后四位数
                    String sitCodeLast = stiCode.substring(stiCode.lastIndexOf("_")+1);
                    //将数字加一操作
                    String sitCodePlus = iStoreInRecordService.getMaxNumber(sitCodeLast);
                    //合成最终编码
                    stiCode = stiCode.substring(0,stiCode.lastIndexOf("_"))+"_"+sitCodePlus;
                }
                StoreInRecord storeInRecord = new StoreInRecord();
                storeInRecord.setStirId(UUID.randomUUID().toString().replace("-",""));
                storeInRecord.setStId(stId);
                storeInRecord.setStiCode(stiCode);
                //填写入库方式
                storeInRecord.setStoreWay("2");
                //同一次入库标识
                storeInRecord.setSameRecord(uuid);
                storeInRecord.setKcCumulative(curStoreNum);
                storeInRecord.setStoreNum(Double.valueOf(storeNums[index]));
                storeInRecord.setPushPerson(userId);
                storeInRecord.setPushDate(StringUtils.isEmpty(pushDates[index]) == false?sdf.parse(pushDates[index]):new Date());
                storeInRecord.setRemark(remarks[index]);
                storeInRecord.setCreateBy(userId);
                storeInRecord.setCreateDate(new Date());
                iStoreInRecordService.insert(storeInRecord);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public Store getStoreById(String coId, String maId,String storeNum) throws Exception{
        Store store = new Store();
        EntityWrapper<Store> ew = new EntityWrapper<>();
        ew.eq("coId",coId);
        ew.eq("maId",maId);
        List<Store> stores = storeMapper.selectList(ew);
        if(stores.size() > 0){
            store = stores.get(0);
            Double storeNumResult = store.getStoreNum() + Double.valueOf(storeNum);
            store.setStoreNum(storeNumResult);
            storeMapper.updateById(store);
        }else{
            store.setCoId(coId);
            store.setMaId(maId);
            store.setStoreNum(Double.valueOf(storeNum));
            storeMapper.insert(store);
        }
        return store;
    }

}
